#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月20日

@author: Administrator
'''
import sys
from django.core.management.base import BaseCommand
from optparse import make_option
from common.utils.storage import listdir
from attachment import settings
from attachment.utils import update_oss_file_to_es

class Command(BaseCommand):
    """
    **插入数据到es*
    """
    option_list = BaseCommand.option_list + (
        make_option('-s', '--start_id', action='store', dest='start_id',
                    type='int', default='0', help=u'Records of the query starting ID from the database, default:0'),
        make_option('-e', '--end_id', action='store', dest='end_id',
                    type='int', default='100', help=u'Records of the query starting ID from the database, default:0'),
        make_option('-u', '--debug', action='store', dest='debug',
                type='string', default='false', help=u'Whether to open the debug If debug=true ,will print log  if debug=false ,it will print nothing'),
    )
    def handle(self, *args, **options):
        self.start_id = options['start_id']
        self.end_id = options['end_id']
        self.debug = options['debug']
        #查询数据
        for id in range(self.start_id, self.end_id + 1):
            dir_path = "%s%s/" % (settings.ARTICLE_MEDIA_PATH, id)
            dirs = listdir(dir_path)
            actions = []
            for dir in dirs:
                actions.append("%s%s" % (dir_path, dir))
            update_oss_file_to_es(actions)
        #同步日志
        out_write = "sync article list start_id:%s,end_id:%s success" % (self.start_id, self.end_id)
        #输出同步日志
        self.sys_stdout_write(out_write)
        #换行
        self.sys_stdout_write("\n")
        
    def sys_stdout_write(self, msg):
        u'''是否在控制台打印信息'''
        if self.debug == 'true':
            sys.stdout.write(msg)
